<script setup>
import { ref, onMounted } from 'vue'

// 消息列表数据
const notifications = ref([])
const hasUnread = ref(false)

onMounted(() => {
  // 从本地存储加载消息
  loadNotifications()
})

// 加载消息列表
function loadNotifications() {
  try {
    const savedNotifications = uni.getStorageSync('notifications')
    if (savedNotifications) {
      notifications.value = JSON.parse(savedNotifications)
      checkUnreadStatus()
    } else {
      // 如果没有保存的消息，创建一些示例消息
      createSampleNotifications()
    }
  } catch (e) {
    console.error('加载消息失败', e)
    createSampleNotifications()
  }
}

// 创建示例消息
function createSampleNotifications() {
  const currentDate = new Date()
  
  const sampleNotifications = [
    {
      id: 1,
      title: '健康提醒',
      content: '今天是您的体检预约日，请记得按时前往医院进行体检。',
      time: new Date(currentDate.getTime() - 1000 * 60 * 60 * 2).toISOString(), // 2小时前
      read: false,
      type: 'reminder'
    },
    {
      id: 2,
      title: '系统通知',
      content: '您的会员服务将在7天后到期，请及时续费以继续享受会员权益。',
      time: new Date(currentDate.getTime() - 1000 * 60 * 60 * 24).toISOString(), // 1天前
      read: false,
      type: 'system'
    },
    {
      id: 3,
      title: '活动通知',
      content: '新的健康讲座已上线，点击查看详情并参与互动赢取健康积分。',
      time: new Date(currentDate.getTime() - 1000 * 60 * 60 * 24 * 3).toISOString(), // 3天前
      read: true,
      type: 'activity'
    },
    {
      id: 4,
      title: '健康报告',
      content: '您的最新健康报告已生成，请查看了解您的健康状况。',
      time: new Date(currentDate.getTime() - 1000 * 60 * 60 * 24 * 5).toISOString(), // 5天前
      read: true,
      type: 'report'
    }
  ]
  
  notifications.value = sampleNotifications
  uni.setStorageSync('notifications', JSON.stringify(sampleNotifications))
  checkUnreadStatus()
}

// 检查是否有未读消息
function checkUnreadStatus() {
  hasUnread.value = notifications.value.some(item => !item.read)
}

// 标记消息为已读
function markAsRead(id) {
  const notification = notifications.value.find(item => item.id === id)
  if (notification && !notification.read) {
    notification.read = true
    uni.setStorageSync('notifications', JSON.stringify(notifications.value))
    checkUnreadStatus()
  }
}

// 标记所有消息为已读
function markAllAsRead() {
  if (!hasUnread.value) return
  
  notifications.value.forEach(item => {
    item.read = true
  })
  
  uni.setStorageSync('notifications', JSON.stringify(notifications.value))
  hasUnread.value = false
  
  uni.showToast({
    title: '全部已读',
    icon: 'success'
  })
}

// 删除消息
function deleteNotification(id) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条消息吗？',
    success: (res) => {
      if (res.confirm) {
        notifications.value = notifications.value.filter(item => item.id !== id)
        uni.setStorageSync('notifications', JSON.stringify(notifications.value))
        checkUnreadStatus()
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 清空所有消息
function clearAllNotifications() {
  if (notifications.value.length === 0) return
  
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有消息吗？',
    success: (res) => {
      if (res.confirm) {
        notifications.value = []
        uni.setStorageSync('notifications', JSON.stringify([]))
        hasUnread.value = false
        
        uni.showToast({
          title: '已清空',
          icon: 'success'
        })
      }
    }
  })
}

// 格式化时间
function formatTime(timeString) {
  const date = new Date(timeString)
  const now = new Date()
  
  const diffMs = now - date
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)
  
  if (diffDay > 0) {
    return diffDay + '天前'
  } else if (diffHour > 0) {
    return diffHour + '小时前'
  } else if (diffMin > 0) {
    return diffMin + '分钟前'
  } else {
    return '刚刚'
  }
}

// 获取消息图标
function getNotificationIcon(type) {
  switch (type) {
    case 'reminder':
      return 'calendar'
    case 'system':
      return 'info-circle'
    case 'activity':
      return 'star'
    case 'report':
      return 'file-text'
    default:
      return 'bell'
  }
}

// 返回上一页
function goBack() {
  try {
    uni.navigateBack({
      fail: () => {
        // 如果返回失败，则跳转到首页
        uni.switchTab({
          url: '/pages/index'
        })
      }
    })
  } catch (e) {
    console.error('返回上一页失败', e)
    // 尝试使用switchTab跳转到首页
    try {
      uni.switchTab({
        url: '/pages/index'
      })
    } catch (err) {
      console.error('跳转首页失败', err)
    }
  }
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="back-button" @tap="goBack">
        <text class="back-icon">〈</text>
      </view>
      <view class="title">消息通知</view>
      <view class="header-actions">
        <text v-if="hasUnread" class="read-all" @tap="markAllAsRead">全部已读</text>
        <text v-if="notifications.length > 0" class="clear-all" @tap="clearAllNotifications">清空</text>
      </view>
    </view>
    
    <view class="notification-list" v-if="notifications.length > 0">
      <view 
        v-for="notification in notifications" 
        :key="notification.id" 
        class="notification-item"
        :class="{ 'unread': !notification.read }"
        @tap="markAsRead(notification.id)"
      >
        <view class="notification-icon" :class="'icon-' + notification.type">
        </view>
        <view class="notification-content">
          <view class="notification-header">
            <text class="notification-title">{{ notification.title }}</text>
            <text class="notification-time">{{ formatTime(notification.time) }}</text>
          </view>
          <text class="notification-text">{{ notification.content }}</text>
        </view>
        <view class="notification-actions">
          <text class="delete-btn" @tap.stop="deleteNotification(notification.id)">删除</text>
        </view>
      </view>
    </view>
    
    <view v-else class="empty-state">
      <view class="empty-icon">📭</view>
      <view class="empty-text">暂无消息通知</view>
      <view class="empty-subtext">新的通知将会显示在这里</view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      font-size: 36rpx;
      color: #333;
    }
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    flex: 1;
    text-align: center;
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    
    .read-all, .clear-all {
      font-size: 26rpx;
      color: #1890ff;
      margin-left: 20rpx;
    }
  }
}

.notification-list {
  padding: 20rpx;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: all 0.3s ease;
  
  &.unread {
    background-color: #f0f7ff;
    
    &::before {
      content: '';
      position: absolute;
      top: 30rpx;
      left: 10rpx;
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      background-color: #1890ff;
    }
  }
  
  .notification-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    &.icon-reminder {
      background-color: #e6f7ff;
      color: #1890ff;
    }
    
    &.icon-system {
      background-color: #fff7e6;
      color: #fa8c16;
    }
    
    &.icon-activity {
      background-color: #f6ffed;
      color: #52c41a;
    }
    
    &.icon-report {
      background-color: #f9f0ff;
      color: #722ed1;
    }
  }
  
  .notification-content {
    flex: 1;
    
    .notification-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      
      .notification-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
      }
      
      .notification-time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .notification-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
    }
  }
  
  .notification-actions {
    margin-left: 20rpx;
    
    .delete-btn {
      font-size: 24rpx;
      color: #ff4d4f;
      padding: 6rpx 12rpx;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
  
  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .empty-subtext {
    font-size: 26rpx;
    color: #999;
  }
}
</style>